<!-- 出货检验单行表格组件 -->
<template>
  <div class="oqc-line-table">
    <el-card v-if="showCard" class="box-card" shadow="hover">
      <div slot="header" class="clearfix">
        <span>检验项列表</span>
        <el-button
          style="float: right; margin-left: 10px"
          type="primary"
          size="mini"
          icon="el-icon-plus"
          @click="handleAdd"
          v-hasPermi="['qc:OutgoingInspection:add']"
        >新增</el-button>
      </div>

      <el-table
        v-loading="loading"
        :data="lineList"
        row-key="lineId"
        border
        :max-height="tableHeight"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center" type="index" width="50" />
        <el-table-column label="检测项编码" align="center" prop="indexCode" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column label="检测项名称" align="center" prop="indexName" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column label="检测项类型" align="center" prop="indexType" min-width="120">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.indexType === '1'" type="info">外观</el-tag>
            <el-tag v-else-if="scope.row.indexType === '2'" type="success">视觉</el-tag>
            <el-tag v-else-if="scope.row.indexType === '3'" type="warning">尺寸</el-tag>
            <el-tag v-else-if="scope.row.indexType === '4'" type="primary">物理性能检测</el-tag>
            <el-tag v-else-if="scope.row.indexType === '5'" type="danger">化学成分检测</el-tag>
            <span v-else>{{ scope.row.indexType }}</span>
          </template>
        </el-table-column>
        <el-table-column label="标准值" align="center" prop="standerVal" min-width="100" />
        <el-table-column label="检测要求" align="center" prop="checkMethod" min-width="150" :show-overflow-tooltip="true" />
        <el-table-column label="检测工具" align="center" prop="qcTool" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column label="上限" align="center" prop="thresholdMax" min-width="80" />
        <el-table-column label="下限" align="center" prop="thresholdMin" min-width="80" />
        <el-table-column label="单位" align="center" prop="unit" min-width="80" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['qc:OutgoingInspection:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['qc:OutgoingInspection:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改检验项对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="检测项编码" prop="indexCode">
              <el-input v-model="form.indexCode" placeholder="请输入检测项编码">
                <el-button slot="append" icon="el-icon-search" @click="openIndexSelector"></el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检测项名称" prop="indexName">
              <el-input v-model="form.indexName" placeholder="请输入检测项名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="检测项类型" prop="indexType">
              <el-select v-model="form.indexType" placeholder="请选择检测项类型" style="width: 100%">
                <el-option label="外观" value="1" />
                <el-option label="视觉" value="2" />
                <el-option label="尺寸" value="3" />
                <el-option label="物理性能检测" value="4" />
                <el-option label="化学成分检测" value="5" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检测工具" prop="qcTool">
              <el-input v-model="form.qcTool" placeholder="请输入检测工具" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="10">
            <el-form-item label="标准值" prop="standerVal">
              <el-input-number v-model="form.standerVal" placeholder="请输入标准值" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="上限" prop="thresholdMax">
              <el-input-number v-model="form.thresholdMax" placeholder="请输入上限" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="下限" prop="thresholdMin">
              <el-input-number v-model="form.thresholdMin" placeholder="请输入下限" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="10">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="form.unit" placeholder="请输入单位" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="检测要求" prop="checkMethod">
          <el-input v-model="form.checkMethod" type="textarea" placeholder="请输入检测要求" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 检测项选择器对话框 -->
    <el-dialog title="选择检测项" :visible.sync="indexSelectorVisible" width="800px" append-to-body>
      <div class="search-container">
        <el-form :inline="true" :model="indexQueryParams" class="demo-form-inline">
          <el-form-item label="检测项编码">
            <el-input v-model="indexQueryParams.indexCode" placeholder="请输入检测项编码" clearable />
          </el-form-item>
          <el-form-item label="检测项名称">
            <el-input v-model="indexQueryParams.indexName" placeholder="请输入检测项名称" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchIndexList">查询</el-button>
            <el-button @click="resetIndexQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table
        v-loading="indexLoading"
        :data="indexList"
        row-key="record_id"
        border
        height="400"
        @row-click="handleIndexSelect"
        highlight-current-row
      >
        <el-table-column label="序号" align="center" type="index" width="50" />
        <el-table-column label="检测项编码" align="center" prop="index_code" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column label="检测项名称" align="center" prop="index_name" min-width="150" :show-overflow-tooltip="true" />
        <el-table-column label="检测项类型" align="center" prop="index_type" min-width="120">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.index_type === '1'" type="info">外观</el-tag>
            <el-tag v-else-if="scope.row.index_type === '2'" type="success">视觉</el-tag>
            <el-tag v-else-if="scope.row.index_type === '3'" type="warning">尺寸</el-tag>
            <el-tag v-else-if="scope.row.index_type === '4'" type="primary">物理性能检测</el-tag>
            <el-tag v-else-if="scope.row.index_type === '5'" type="danger">化学成分检测</el-tag>
            <span v-else>{{ scope.row.index_type }}</span>
          </template>
        </el-table-column>
        <el-table-column label="标准值" align="center" prop="stander_val" min-width="100" />
        <el-table-column label="检测要求" align="center" prop="check_method" min-width="150" :show-overflow-tooltip="true" />
        <el-table-column label="检测工具" align="center" prop="qc_tool" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column label="上限" align="center" prop="threshold_max" min-width="80" />
        <el-table-column label="下限" align="center" prop="threshold_min" min-width="80" />
        <el-table-column label="单位" align="center" prop="unit" min-width="80" />
      </el-table>

      <pagination
        v-show="indexTotal > 0"
        :total="indexTotal"
        :page.sync="indexQueryParams.pageNum"
        :limit.sync="indexQueryParams.pageSize"
        @pagination="getIndexList"
      />

      <div slot="footer" class="dialog-footer">
        <el-button @click="indexSelectorVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listQcOqcLine, addQcOqcLine, updateQcOqcLine, deleteQcOqcLine } from "@/api/qc/OutgoingInspection";
import { selectQcTemplateIndexList } from "@/api/qc/QualitySchemeOrder";

export default {
  name: "OqcLineTable",
  props: {
    // 出货检验单ID
    oqcId: {
      type: [Number, String],
      default: null
    },
    // 是否可编辑
    editable: {
      type: Boolean,
      default: true
    },
    // 检测方案ID，用于关联检测项选择
    templateId: {
      type: [Number, String],
      default: 1
    },
    // 是否显示卡片（新增模式下不显示）
    showCard: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格高度
      tableHeight: 300,
      // 检验项表格数据
      lineList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        oqcId: null
      },
      // 表单参数
      form: {
        lineId: null,
        oqcId: null,
        indexId: null,
        indexCode: null,
        indexName: null,
        indexType: "3", // 默认尺寸
        qcTool: null,
        checkMethod: null,
        standerVal: null,
        unit: null,
        thresholdMax: null,
        thresholdMin: null,
        crQuantityNum: 0,
        majQuantityNum: 0,
        minQuantityNum: 0,
        attr1: null,
        attr2: null,
        attr3: null,
        attr4: null
      },
      // 表单校验
      rules: {
        indexCode: [
          { required: true, message: "检测项编码不能为空", trigger: "blur" }
        ],
        indexName: [
          { required: true, message: "检测项名称不能为空", trigger: "blur" }
        ],
        indexType: [
          { required: true, message: "检测项类型不能为空", trigger: "change" }
        ],
        checkMethod: [
          { required: true, message: "检测要求不能为空", trigger: "blur" }
        ]
      },
      // 检测项选择器相关数据
      indexSelectorVisible: false,
      indexLoading: false,
      indexList: [],
      indexTotal: 0,
      indexQueryParams: {
        pageNum: 1,
        pageSize: 10,
        indexCode: "",
        indexName: ""
      }
    };
  },
  watch: {
    oqcId: {
      handler(val) {
        if (val) {
          // 确保 oqcId 是数字类型
          this.queryParams.oqcId = Number(val);
          this.getList();
        } else {
          this.lineList = [];
          this.total = 0;
        }
      },
      immediate: true
    }
  },
  mounted() {
    // 计算表格高度
    this.calculateTableHeight();
    window.addEventListener('resize', this.calculateTableHeight);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.calculateTableHeight);
  },
  methods: {
    // 计算表格高度
    calculateTableHeight() {
      this.tableHeight = window.innerHeight - 400; // 根据实际情况调整
      if (this.tableHeight < 200) {
        this.tableHeight = 200;
      }
    },
    /** 查询检验项列表 */
    getList() {
      if (!this.oqcId) {
        console.warn("检验项列表查询：oqcId 为空，无法查询");
        return;
      }
      this.loading = true;
      
      // 根据后端日志，参数需要与QcOqcLine实体类的属性名完全匹配
      // 创建一个QcOqcLine对象，只设置oqcId属性
      const data = {
        oqcId: Number(this.oqcId),
        // 添加分页参数（RuoYi框架会自动处理这些参数）
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize
      };
      
      console.log("检验项列表查询参数:", data);
      
      // 修改API调用，传入业务参数和分页参数
      listQcOqcLine(data).then(response => {
        console.log("检验项列表查询成功:", response);
        this.lineList = response.rows || [];
        this.total = response.total || 0;
        this.loading = false;
      }).catch((error) => {
        console.error("获取检验项列表失败:", error);
        // 添加更详细的错误信息
        if (error.response) {
          console.error("错误响应数据:", error.response.data);
          console.error("错误状态码:", error.response.status);
          console.error("错误头信息:", error.response.headers);
        } else if (error.request) {
          console.error("请求未收到响应:", error.request);
        } else {
          console.error("请求配置错误:", error.config);
        }
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        lineId: null,
        oqcId: this.oqcId ? Number(this.oqcId) : null,
        indexId: null,
        indexCode: null,
        indexName: null,
        indexType: "3", // 默认尺寸
        qcTool: null,
        checkMethod: null,
        standerVal: null,
        unit: null,
        thresholdMax: null,
        thresholdMin: null,
        crQuantityNum: 0,
        majQuantityNum: 0,
        minQuantityNum: 0,
        attr1: null,
        attr2: null,
        attr3: null,
        attr4: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.lineId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加检验项";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const lineId = row.lineId || this.ids[0];
      // 直接使用行数据填充表单
      this.form = { ...row };
      this.open = true;
      this.title = "修改检验项";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 确保设置了出货检验单ID，并且是数字类型
          this.form.oqcId = Number(this.oqcId);
          
          if (this.form.lineId != null) {
            updateQcOqcLine(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).catch(error => {
              console.error("修改检验项失败:", error);
            });
          } else {
            addQcOqcLine(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).catch(error => {
              console.error("新增检验项失败:", error);
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const lineIds = row.lineId || this.ids[0];
      this.$modal.confirm('是否确认删除检验项编号为"' + lineIds + '"的数据项?').then(function() {
        return deleteQcOqcLine(lineIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 获取所有检验项数据（供父组件使用）
    getAllLineData() {
      return this.lineList;
    },
    
    // 设置卡片显示状态（供父组件调用）
    setCardVisibility(visible) {
      this.showCard = visible;
    },
    
    // 完全重置组件状态（供父组件调用）
    reset() {
      this.lineList = [];
      this.total = 0;
      this.loading = false;
      this.ids = [];
      this.single = true;
      this.multiple = true;
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        oqcId: this.oqcId
      };
      // 重置表单
      this.resetForm("form");
    },
    
    // 打开检测项选择器
    openIndexSelector() {
      this.indexSelectorVisible = true;
      this.resetIndexQuery();
      this.getIndexList();
    },
    // 获取检测项列表
    getIndexList() {
      this.indexLoading = true;
      // 使用props中传入的templateId
      const templateId = Number(this.templateId);
      
      // 获取查询参数
      const queryParams = this.getIndexQueryParams();
      
      console.log("检测项查询参数:", templateId, queryParams);
      
      selectQcTemplateIndexList(templateId, queryParams).then(response => {
        console.log("检测项列表查询成功:", response);
        this.indexList = response.rows || [];
        this.indexTotal = response.total || 0;
        this.indexLoading = false;
      }).catch((error) => {
        console.error("获取检测项列表失败:", error);
        this.indexLoading = false;
      });
    },
    // 搜索检测项列表
    searchIndexList() {
      this.indexQueryParams.pageNum = 1;
      this.getIndexList();
    },
    // 重置检测项查询条件
    resetIndexQuery() {
      this.indexQueryParams = {
        pageNum: 1,
        pageSize: 10,
        indexCode: "",
        indexName: ""
      };
    },
    
    // 获取检测项查询参数
    getIndexQueryParams() {
      const params = {
        pageNum: this.indexQueryParams.pageNum,
        pageSize: this.indexQueryParams.pageSize
      };
      
      // 添加检测项编码和名称条件
      if (this.indexQueryParams.indexCode) {
        params.index_code = this.indexQueryParams.indexCode;
      }
      
      if (this.indexQueryParams.indexName) {
        params.index_name = this.indexQueryParams.indexName;
      }
      
      return params;
    },
    // 选择检测项
    handleIndexSelect(row) {
      // 将选中的检测项数据回显到表单中
      // 根据数据库字段名称进行映射
      this.form.indexId = row.index_id;
      this.form.indexCode = row.index_code;
      this.form.indexName = row.index_name;
      this.form.indexType = row.index_type;
      this.form.standerVal = row.stander_val;
      this.form.checkMethod = row.check_method;
      this.form.qcTool = row.qc_tool;
      this.form.thresholdMax = row.threshold_max;
      this.form.thresholdMin = row.threshold_min;
      this.form.unit = row.unit;
      
      // 关闭选择器对话框
      this.indexSelectorVisible = false;
      
      this.$message.success("检测项选择成功");
    }
  }
};
</script>

<style scoped>
.oqc-line-table {
  margin-top: 15px;
}

.box-card {
  margin-bottom: 15px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}

/* 表格内容垂直居中 */
::v-deep .el-table td {
  padding: 8px 0;
}

/* 表单项间距 */
.el-form-item {
  margin-bottom: 18px;
}

/* 行间距 */
.el-row {
  margin-bottom: 10px;
}

/* 检测项选择器样式 */
.search-container {
  margin-bottom: 15px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.search-container .el-form-item {
  margin-bottom: 0;
}

/* 表格行点击高亮 */
::v-deep .el-table__row:hover {
  cursor: pointer;
}

::v-deep .el-table__row.current-row {
  background-color: #e6f7ff !important;
}
</style> 